package com.kingdee.pda.ui.replenish_grounding;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.basecommon.utils.PreferencesUtils;
import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.R;
import com.kingdee.pda.commonmethod.QuerySkuBindLocationPresenter;
import com.kingdee.pda.commonmethod.QuerySkuBindLocationView;
import com.kingdee.pda.commonmethod.CheckSkuPresenter;
import com.kingdee.pda.commonmethod.CheckSkuView;
import com.kingdee.pda.commonmethod.QueryStockPresenter;
import com.kingdee.pda.commonmethod.QueryStockView;
import com.kingdee.pda.entity.Goods;
import com.kingdee.pda.entity.LocationListBean;
import com.kingdee.pda.entity.SkuBindLocationsBean;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.entity.WarehouseLocation;
import com.kingdee.pda.plugins.http.common.OnRequestCallback;
import com.kingdee.pda.plugins.http.serverinterface.IMoveOperate;
import com.kingdee.pda.plugins.http.serverinterface.impl.MoveOperateImpl;
import com.kingdee.pda.ui.activity.BaseTitleActivity;
import com.kingdee.pda.ui.activity.QueryLocationStockActivity;
import com.kingdee.pda.ui.dialog.RemindDialog;
import com.kingdee.pda.ui.popupwindow.FastMoveInLocationsSelectorPpWindow;
import com.kingdee.pda.ui.popupwindow.ListSelectorPpWindow;
import com.kingdee.pda.util.CommonUtil;
import com.kingdee.pda.util.GlideUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 补货上架操作
 * Created by dlj
 * DATE 2021/8/18
 * TIME 9:25
 */
public class ReplenishGroundingActivity extends BaseTitleActivity implements View.OnKeyListener, QueryStockView, QuerySkuBindLocationView, CheckSkuView {
    private EditText et_transferLocationcode, et_skuCode, et_actul_locationCode, et_grounding_count, et_invStatusName;
    private TextView tv_recommed_skuName, tv_recommed_locationCode;
    private ImageView mIvGoodsPic;
    private TextView mTvSkuNum;
    private TextView mTvSkuName;
    private TextView mTvGoodsBarcode;
    private Button mBtnConfirm;
    private LinearLayout mLlMoveInLocation;
    private WarehouseLocation mMoveOutLocation;
    private WarehouseLocation mMoveInLocation;

    private Goods mOperateGoods;  //商品操作对象
    private SkuBindLocationsBean result;
    private RemindDialog mOperateConfirmDialog;
    private FastMoveInLocationsSelectorPpWindow<WarehouseLocation> locationSelector;
    private int mCanMoveQty = 0;
    private boolean autoShelves;
    private boolean isScanMoveInLocation = false;
    private QueryStockPresenter queryStockPresenter;
    private boolean isMoveOut = true;
    private QuerySkuBindLocationPresenter querySkuBindLocationPresenter;
    private CheckSkuPresenter checkSkuPresenter;
    private List<LocationListBean> locationListBeanList = new ArrayList<>();

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, ReplenishGroundingActivity.class));
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_replenish_grounding);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("补货上架");

        et_transferLocationcode = findViewById(R.id.et_transferLocationcode);
        et_skuCode = findViewById(R.id.et_skuCode);
        et_actul_locationCode = findViewById(R.id.et_actul_locationCode);
        et_grounding_count = findViewById(R.id.et_grounding_count);
        et_invStatusName = findViewById(R.id.et_invStatusName);

        setEditTextScannerEvents(et_transferLocationcode, this);
        setEditTextScannerEvents(et_skuCode, this);
        setEditTextScannerEvents(et_actul_locationCode, this);
        setEditTextScannerEvents(et_grounding_count, this);

        tv_recommed_skuName = findViewById(R.id.tv_recommed_skuName);
        tv_recommed_locationCode = findViewById(R.id.tv_recommed_locationCode);

        mIvGoodsPic = findViewById(R.id.iv_goods_pic);
        mTvSkuNum = findViewById(R.id.tv_sku_num);
        mTvSkuName = findViewById(R.id.tv_sku_name);
        mTvGoodsBarcode = findViewById(R.id.tv_goods_barcode);
        mLlMoveInLocation = findViewById(R.id.ll_actulLocationcode);

        mBtnConfirm = findViewById(R.id.btn_confirm);
        mBtnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showOperateConfirmDialog();
            }
        });
        findViewById(R.id.iv_select).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDefaultMoveInSelector();
            }
        });
        findViewById(R.id.iv_select_invStatusName).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showInvStatusNameSelector();
            }
        });
        autoShelves = PreferencesUtils.getBoolean(this, "autoShelves");
        if (autoShelves) {
            mBtnConfirm.setVisibility(View.INVISIBLE);
        } else {
            mBtnConfirm.setVisibility(View.VISIBLE);
        }

        queryStockPresenter = new QueryStockPresenter(this, this);
        querySkuBindLocationPresenter = new QuerySkuBindLocationPresenter(this, this);
        checkSkuPresenter = new CheckSkuPresenter(this, this);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (!(v instanceof EditText)) {
            return false;
        }
        EditText editText = (EditText) v;
        String input = editText.getText().toString().trim();
        if ((keyCode == KeyEvent.KEYCODE_SYSRQ || keyCode == KeyEvent.KEYCODE_ENTER) && event.getAction() == KeyEvent.ACTION_UP) {
            switch (v.getId()) {
                case R.id.et_transferLocationcode:
                    queryLocationInfo(input, true);
                    break;
                case R.id.et_skuCode:
                    if (mMoveOutLocation == null) {
                        SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "请选择移出库位", false, false);
                    } else {
                        String skuSplit = CommonUtil.skuCodeSplit(ReplenishGroundingActivity.this, input);
                        if (TextUtils.isEmpty(skuSplit)) {
                            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "商品条码截取结果为空，请检查输入和截图规则", false, false);
                            return true;
                        }
                        et_skuCode.setText(skuSplit);
                        queryGoodsInfo(skuSplit);
                    }
                    break;
                case R.id.et_actul_locationCode:
                    queryLocationInfo(input, false);
                    break;
                case R.id.et_grounding_count:
                    if (Integer.parseInt(input) > mCanMoveQty) {
                        et_grounding_count.setText(String.valueOf(mCanMoveQty));
                        et_grounding_count.setSelection(et_grounding_count.getText().length());
                    }

                    if (autoShelves) showOperateConfirmDialog();
                    break;
            }
            return true;
        }
        return false;
    }

    /**
     * 查询库位信息
     *
     * @param locationNum 库位编码
     * @param isMoveOut   是否为移出仓库
     */
    private void queryLocationInfo(String locationNum, final boolean isMoveOut) {
        this.isMoveOut = isMoveOut;
        queryStockPresenter.queryWarehouseLocation(getCurrentWarehouse().getId(), locationNum);
    }

    //查询库位库存信息
    private void queryGoodsLocationStock(final WarehouseLocation location) {
        if (mOperateGoods == null) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "请扫描或输入商品条码并按enter", false, false);
            CommonUtil.requestFocusAndNoClearText(et_skuCode);
            return;
        }

        queryStockPresenter.queryGoodsLocationStock(location, mOperateGoods.getSkuId(), location.getLocationId() == 0 ? 1 : 0);
    }

    //查询商品信息
    private void queryGoodsInfo(String barcode) {
        checkSkuPresenter.queryGoods(getCurrentWarehouse().getId(), mMoveOutLocation.getLocationId(), barcode);
    }

    //查询该sku绑定的移入库位列表
    private void queryLocationStockInfo() {
        if (mOperateGoods == null) return;
        querySkuBindLocationPresenter.queryGoodsLocation(getCurrentWarehouse().getId(), mOperateGoods.getSkuCode());
    }

    /**
     * 展示移库操作确认框
     */
    private void showOperateConfirmDialog() {
        if (getCurrentWarehouse() == null) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "仓库信息获取失败", false, false);
            return;
        }
        if (mMoveOutLocation == null) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "中转库位信息获取失败", false, false);
            return;
        }
        if (mOperateGoods == null) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "商品信息获取失败", false, false);
            return;
        }
        if (mMoveInLocation == null) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "实际上架库位信息获取失败", false, false);
            return;
        }
        if ((mMoveInLocation.getLocationId() + "").equals(mMoveOutLocation.getLocationId() + "") || et_transferLocationcode.getText().toString().equals(et_actul_locationCode.getText().toString())) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "中转库位和实际上架库位不能一样", false, false);
            return;
        }
        if (mCanMoveQty == 0) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "商品可移库数量为0", false, false);
            return;
        }
        int moveQty = CommonUtil.formatStringToInt(et_grounding_count.getText().toString().trim());
        if (moveQty == 0) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "请输入移库数量", false, false);
            return;
        }
        if (mOperateConfirmDialog == null) {
            mOperateConfirmDialog = new RemindDialog(ReplenishGroundingActivity.this);
        }
        mOperateConfirmDialog.setTitle("确认");
        mOperateConfirmDialog.setContent(getOperateContent());
        mOperateConfirmDialog.setShowCancelButton();
        mOperateConfirmDialog.setListener(new RemindDialog.OnConfirmClickListener() {
            @Override
            public void onConfirmClick() {
                requestMoveOperate();
            }
        });
        mOperateConfirmDialog.show();
    }

    private String getOperateContent() {
        StringBuffer sb = new StringBuffer();
        sb.append("SKU 名称：" + mOperateGoods.getSpecName());
        sb.append("\n");
        sb.append("移出库位：" + mMoveOutLocation.getLocationName());
        sb.append("\n");
        sb.append("移入库位：" + mMoveInLocation.getLocationName());
        sb.append("\n");
        sb.append("移动数量：" + CommonUtil.formatStringToInt(et_grounding_count.getText().toString().trim()));
        return sb.toString();
    }

    private void calculateCanMoveQty() {
        if (mMoveOutLocation == null || mMoveInLocation == null) {
            return;
        }

        //可移入量 = 库位的库容 - 库位库存数 - 该库位待移入数量
        int canMoveInQty = mMoveInLocation.getCanMoveInQty();
        if (canMoveInQty <= 0) {
            SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "移入库位没有可用库容量！", false, true);
            et_grounding_count.setEnabled(false);
            mBtnConfirm.setEnabled(false);
        } else {
            //可移出数量
            int canMoveOutQty = mMoveOutLocation.getCanMoveOutQty();
            mCanMoveQty = canMoveInQty > canMoveOutQty ? canMoveOutQty : canMoveInQty;
            if (mCanMoveQty == Integer.MAX_VALUE) {
                SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "最多可以移入数量：无限制！", false, true);
            } else {
                SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "* 最多可以移入数量：" + mCanMoveQty, false, true);
            }
            et_grounding_count.setEnabled(true);
            mBtnConfirm.setEnabled(true);
            et_grounding_count.setText(mCanMoveQty + "");
            CommonUtil.requestFocusAndNoClearText(et_grounding_count);
        }
    }


    /**
     * 展示默认移入库位选择框
     */
    private void showDefaultMoveInSelector() {
        try {
            List<WarehouseLocation> itemLocations = result.getItemLocations();
            List<WarehouseLocation> whLocationList = new ArrayList<>();
            for (int i = 0; i < itemLocations.size(); i++) {
                WarehouseLocation whLocation = itemLocations.get(i);
                if (whLocation.getReplenishSort() > 0)
                    whLocationList.add(whLocation);

                if (i == 0) tv_recommed_locationCode.setText(whLocation.getLocationCode());
            }
            //根据推荐顺序排序
            Collections.sort(whLocationList, new Comparator<WarehouseLocation>() {
                public int compare(WarehouseLocation e1, WarehouseLocation e2) {
                    return e1.getReplenishSort() - e2.getReplenishSort();
                }
            });

            locationSelector = new FastMoveInLocationsSelectorPpWindow<>(ReplenishGroundingActivity.this,
                    R.drawable.shape_bg_edit_selected,
                    mLlMoveInLocation.getWidth(),
                    whLocationList,
                    new FastMoveInLocationsSelectorPpWindow.onItemSelectedListener() {
                        @Override
                        public void onItemSelected(Object item) {
                            WarehouseLocation warehouseLocation = ((WarehouseLocation) item);
                            String input = warehouseLocation.getLocationName();
                            if (mOperateGoods == null) {
                                SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "请先扫描或录入商品！", false, true);
                            }
                            if (input.equals(et_transferLocationcode.getText().toString().trim())) {
                                SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "移入库位不可与移出库位相同！", false, true);
                            }
                            et_actul_locationCode.setText(warehouseLocation.getLocationCode());
                            queryLocationInfo(warehouseLocation.getLocationCode(), false);
                        }
                    });
            locationSelector.showAsDropDown(mLlMoveInLocation, 0, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 展示库存状态选择框
     */
    private void showInvStatusNameSelector() {
        ListSelectorPpWindow<LocationListBean> locationSelector = new ListSelectorPpWindow<>(ReplenishGroundingActivity.this,
                R.drawable.shape_bg_edit_selected,
                et_invStatusName.getWidth(),
                locationListBeanList,
                new ListSelectorPpWindow.onItemSelectedListener() {
                    @Override
                    public void onItemSelected(Object item) {
                        LocationListBean locationListBean = ((LocationListBean) item);
                        mMoveOutLocation.setSelectedStatusBean(locationListBean);
                        et_invStatusName.setText(locationListBean.getInvStatusName());
                        calculateCanMoveQty();
                        if (TextUtils.isEmpty(et_actul_locationCode.getText().toString())) {
                            CommonUtil.requestFocusAndNoClearText(et_actul_locationCode);
                        } else {
                            CommonUtil.requestFocusAndNoClearText(et_grounding_count);
                        }
                    }
                });
        locationSelector.showAsDropDown(et_invStatusName, 0, 10);
    }

    private void requestMoveOperate() {
        showLoadingDialog();
        IMoveOperate moveOperate = new MoveOperateImpl();
        int moveQty = CommonUtil.formatStringToInt(et_grounding_count.getText().toString().trim());
        moveOperate.requestMoveOperate(mMoveOutLocation.getSelectedStatusBean().getInvStatusId(), getCurrentWarehouse().getId(), mMoveOutLocation.getLocationId(), mMoveInLocation.getLocationId(),
                String.valueOf(mOperateGoods.getSkuId()), moveQty, 0, "3", 2, new OnRequestCallback<String>() {
                    @Override
                    public void onFailedCallback(boolean isRequestCallback, final String errorMsg) {
                        super.onFailedCallback(isRequestCallback, errorMsg);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingDialog();
                                SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, errorMsg, false, false);
                            }
                        });
                    }

                    @Override
                    public void onSuccessCallback(String result, Object object) {
                        super.onSuccessCallback(result, object);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingDialog();
                                SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, "上架成功！", false, true);
                                clearAllView();
                            }
                        });
                    }
                });
    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {
        et_transferLocationcode.setText("");
        mMoveOutLocation = null;
        clearAllView();
        CommonUtil.requestFocusAndClearText(et_transferLocationcode);
    }

    private void initGoodsView() {
        mIvGoodsPic.setImageResource(R.mipmap.image_pic_default);
        mTvSkuNum.setText("SKU 编码：—");
        mTvSkuName.setText("SKU 名称：—");
        mTvGoodsBarcode.setText("商品条码：—");
    }

    private void showGoodsView() {
        GlideUtils.loadImage(ReplenishGroundingActivity.this, mOperateGoods.getPictureUrl(), mIvGoodsPic);
        mTvSkuNum.setText("SKU 编码：" + mOperateGoods.getSkuCode());
        mTvSkuName.setText("SKU 名称：" + mOperateGoods.getSpecName());
        mTvGoodsBarcode.setText("商品条码：" + mOperateGoods.getItemBarcode());
        tv_recommed_skuName.setText(mOperateGoods.getSpecName());
        et_actul_locationCode.requestFocus();
    }

    private void clearAllView() {
        mMoveInLocation = null;
        mOperateGoods = null;
        mCanMoveQty = 0;
        et_actul_locationCode.setText("");
        et_invStatusName.setText("");
        et_grounding_count.setText("");
        tv_recommed_skuName.setText("");
        tv_recommed_locationCode.setText("");
        et_invStatusName.setText("");
        initGoodsView();
        mBtnConfirm.setEnabled(false);
        CommonUtil.requestFocusAndClearText(et_skuCode);
    }

    @Override
    public void queryWarehouseLocationSuccess(WarehouseLocation warehouseLocation) {
        //第1步校验移出库位
        if (isMoveOut) {
            mMoveOutLocation = warehouseLocation;
            et_skuCode.requestFocus();
        } else {        //第5步校验移入库位并且查询移入库位库存
            mMoveInLocation = warehouseLocation;
            isScanMoveInLocation = true;
            queryGoodsLocationStock(mMoveInLocation);
        }
    }

    @Override
    public void queryWarehouseLocationFailed(String message) {
        SpeakUtils.speakWithToast(ReplenishGroundingActivity.this, message, false, false);
        if (isMoveOut) {
            et_transferLocationcode.setText("");
            mMoveOutLocation = null;
            et_transferLocationcode.postDelayed(new Runnable() {
                @Override
                public void run() {
                    et_transferLocationcode.requestFocus();
                }
            }, 300);
        } else {
            et_actul_locationCode.setText("");
            mMoveInLocation = null;
            et_actul_locationCode.requestFocus();
        }
    }

    @Override
    public void queryGoodsSuccess(Goods goods) {
        //第2步校验条码
        mOperateGoods = goods;
        showGoodsView();
        isScanMoveInLocation = false;
        isMoveOut = true;
        queryGoodsLocationStock(mMoveOutLocation);  //第3步查询该条码在移出库位的库存
    }

    @Override
    public void queryGoodsFailed(String message) {
        SpeakUtils.speakWithToast(this, message, false, false);
        CommonUtil.requestFocusAndClearText(et_skuCode);
        initGoodsView();
    }

    @Override
    public void queryGoodsLocationSuccess(SkuBindLocationsBean warehouseLocations) {
        result = warehouseLocations;
        if (!isScanMoveInLocation) {
            showDefaultMoveInSelector();
        }
    }

    @Override
    public void queryGoodsLocationFailed(String message) {
        SpeakUtils.speakWithToast(this, message, false, false);
    }

    @Override
    public void queryGoodsLocationStockSuccess(WarehouseLocation warehouseLocation) {
        if (!isMoveOut) {  //第6步选中移入库位，计算能移库的数量
            mMoveInLocation = warehouseLocation;
            calculateCanMoveQty();
        } else {
            mMoveOutLocation = warehouseLocation;
            locationListBeanList.clear();
            locationListBeanList.addAll(mMoveOutLocation.getList());
            //默认选中第一个状态
            if (locationListBeanList.size() > 0) {
                mMoveOutLocation.setSelectedStatusBean(locationListBeanList.get(0));
                et_invStatusName.setText(mMoveOutLocation.getSelectedStatusBean().getInvStatusName());
            }
            //第4步查询该sku绑定的移入库位列表
            queryLocationStockInfo();
        }
    }

    @Override
    public void queryGoodsLocationStockFailed(String message) {
        SpeakUtils.speakWithToast(this, message, false, false);
    }
}
